﻿using UnityEngine;
using System.Collections;
/// <summary>
/// cs版的LoadComponent.因为ICallable暂时无法处理.
/// </summary>
public class LoadComponentL : LoadComponent {
    /// <summary>
    /// 下载过程,进度报告
    /// </summary>
    /// <param name="progress"></param>
    public delegate void LoadProcess(float progress);
    /// <summary>
    /// 下载完毕,内容报告
    /// </summary>
    /// <param name="ab"></param>
    public delegate void LoadComplete(object ab);
    /// <summary>
    /// 进度报告实例.
    /// </summary>
    private LoadProcess onLoadProcess;
    
    /// <summary>
    /// 下载指定url下的unity导出资源.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="version"></param>
    /// <param name="onProcess"></param>
    /// <param name="onComplete"></param>
    /// <returns></returns>
    public IEnumerator Load(string url, int version, LoadProcess onProcess, LoadComplete onComplete)
    {
        onLoadProcess = onProcess;
        if (! AssetBundleDictionary.Contains(url))
        {
            WWW www = Setup(url, version);
            yield return StartCoroutine(WaitForLoading(www));
			AssetBundleDictionary.Add(url,www.assetBundle);
        }
		AssetBundle ab = AssetBundleDictionary.Get(url);
        if (onComplete != null)
        {
            onComplete(ab);
        }
    }
    /// <summary>
    /// 下载指定url的配置信息.T[string,byte[]]
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="onLoadComplete"></param>
    /// <returns></returns>
    public IEnumerator Load<T>(string url, LoadComplete onLoadComplete)
    {
        WWW www = new WWW(url);
        yield return StartCoroutine(WaitForLoading(www));
        if (onLoadComplete != null)
        {
            if(typeof(T) == typeof(string))
                onLoadComplete(www.text);
            if (typeof(T) == typeof(byte[]))
                onLoadComplete(www.bytes);
        }
    }

    new IEnumerator WaitForLoading(WWW www)
    {
        while (!www.isDone)
        {
            if (! string.IsNullOrEmpty(www.error))
            {
                Debug.Log(www.error +"=> url:"+www.url);
                break;
            }
            if (onLoadProcess != null)
            {
                onLoadProcess(www.progress);
            }
			yield return null;
        }
    }
}
